import type { Ref } from 'vue';

import { ref } from 'vue';

import { message } from 'ant-design-vue';

// 聊天消息类型定义
export interface ChatMessage {
  id: string;
  content: string;
  isUser: boolean;
  timestamp: number;
  model?: string;
  avatar?: string;
  nickname?: string;
}

/**
 * 聊天消息管理组合式函数
 * 负责消息的添加、更新和清理
 */
export function useChatMessages(
  selectedModel: Ref<string>,
  userNickname: string,
  userAvatar?: string,
) {
  // 聊天消息列表
  const messages = ref<ChatMessage[]>([]);

  // 加载指示器
  let dotCount = 0;
  let loadingInterval: null | number = null;

  // 生成唯一ID
  const generateId = () => {
    return Date.now().toString(36) + Math.random().toString(36).slice(2);
  };

  // 添加用户消息
  const addUserMessage = (content: string): string => {
    const id = generateId();
    messages.value.push({
      id,
      content,
      isUser: true,
      timestamp: Date.now(),
      model: selectedModel.value,
      avatar: userAvatar,
      nickname: userNickname,
    });
    return id;
  };

  // 添加AI消息
  const addAIMessage = (content: string): string => {
    const id = generateId();
    messages.value.push({
      id,
      content,
      isUser: false,
      timestamp: Date.now(),
      model: selectedModel.value,
      nickname: 'AI助手',
    });
    return id;
  };

  // 更新AI消息内容
  const updateAIMessage = (
    id: string,
    content: ((prev: string) => string) | string,
  ) => {
    const index = messages.value.findIndex((msg) => msg.id === id);
    if (index !== -1) {
      const msg = messages.value[index];
      if (typeof content === 'function') {
        const prevContent = msg.content || '';
        messages.value[index].content = content(prevContent);
      } else {
        messages.value[index].content = content;
      }
    }
  };

  // 启动加载动画
  const startTypingAnimation = (aiMessageId: string) => {
    if (loadingInterval) clearInterval(loadingInterval);

    loadingInterval = window.setInterval(() => {
      dotCount = (dotCount % 3) + 1;
      const dots = '.'.repeat(dotCount);
      updateAIMessage(aiMessageId, `思考中${dots}`);
    }, 500);
  };

  // 停止加载动画
  const stopTypingAnimation = () => {
    if (loadingInterval) {
      clearInterval(loadingInterval);
      loadingInterval = null;
    }
  };

  // 清空对话
  const clearMessages = () => {
    messages.value = [
      {
        id: generateId(),
        content:
          '👋 你好！我是AI助手，有什么我可以帮助你的吗？\n\n你可以向我提问任何问题，我会尽力提供帮助。',
        isUser: false,
        timestamp: Date.now(),
        model: selectedModel.value,
        nickname: 'AI助手',
      },
    ];
    message.success('对话已清空');
  };

  // 初始化欢迎消息
  clearMessages();

  return {
    messages,
    addUserMessage,
    addAIMessage,
    updateAIMessage,
    clearMessages,
    startTypingAnimation,
    stopTypingAnimation,
  };
}
